package site.kitcheng.springboottest.infra.utils;

import site.kitcheng.springboottest.infra.constant.BaseConstant;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * ClassName: KeyConverter
 * Package: site.kitcheng.springboottest.infra.utils
 * Description:
 *
 * @Author jiangCheng
 * @Create 2025/2/24 11:26
 * @Version 1.0
 */
public class KeyConverter {
    // 从 Base64 字符串恢复公钥
    public static PublicKey getPublicKeyFromBase64(String base64PublicKey) throws Exception {
        byte[] decodedKey = Base64.getDecoder().decode(base64PublicKey);
        // 使用 RSA 算法
        KeyFactory keyFactory = KeyFactory.getInstance(BaseConstant.ENCRYPTION_ALGORITHMS);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }

    // 从 Base64 字符串恢复私钥
    public static PrivateKey getPrivateKeyFromBase64(String base64PrivateKey) throws Exception {
        byte[] decodedKey = Base64.getDecoder().decode(base64PrivateKey);
        // 使用 RSA 算法
        KeyFactory keyFactory = KeyFactory.getInstance(BaseConstant.ENCRYPTION_ALGORITHMS);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }
}
